package com.charley.icloud.common.exception.handler;

import com.charley.icloud.common.exception.DefaultException;
import com.charley.icloud.common.response.result.HttpResponseResult;
import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * 全局异常处理
 * TODO: 获取根据业务来继续完善该处理器
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 全局异常的处理
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public HttpResponseResult exceptionHandler(Exception e) {
        e.printStackTrace();
        HttpResponseResult responseResult = new HttpResponseResult();
        responseResult.setData(null);
        return responseResult.error("程序异常,请联系管理员~~~~~~");
    }

    /**
     * 参数校验全局异常处理
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public HttpResponseResult methodArgumentNotValidException(MethodArgumentNotValidException e) {
        e.printStackTrace();
        ObjectError error = e.getBindingResult().getAllErrors().get(0);
        HttpResponseResult responseResult = new HttpResponseResult();
        responseResult.setData(null);
        return responseResult.error(error.getDefaultMessage());
    }

    /**
     * 默认异常的处理
     */
    @ExceptionHandler(value = DefaultException.class)
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public HttpResponseResult defaultExceptionHandler(DefaultException e) {
        e.printStackTrace();
        HttpResponseResult responseResult = new HttpResponseResult();
        responseResult.setData(null);
        return responseResult.error(e.getStatus(), e.getMessage());
    }
}
